package com.shunda.ysdgj.manager.service.impl.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shunda.ysdgj.common.exception.CustomException;
import com.shunda.ysdgj.common.util.ValidateUtil;
import com.shunda.ysdgj.manager.mapper.system.SysUserRoleMapper;
import com.shunda.ysdgj.manager.service.system.SysUserRoleService;
import com.shunda.ysdgj.model.entity.system.SysUserRole;
import com.shunda.ysdgj.model.vo.ResultCodeEnum;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService, IService<SysUserRole> {

    // 获取某个管理员已分配角色的ID
    public List<Long> getAssignedRoleIds(Long userId) {
        if (ValidateUtil.isNotLong(userId)) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }
        return lambdaQuery()
                .eq(SysUserRole::getUserId, userId)
                .list().stream()
                .map(SysUserRole::getRoleId).toList();
    }

    // 为管理员分配角色
    @Transactional
    public boolean add(List<SysUserRole> userRoleList) {
        if (userRoleList.isEmpty()) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }
        Long userId = userRoleList.get(0).getUserId();
        LambdaQueryWrapper<SysUserRole> baseWrapper = new LambdaQueryWrapper<>();
        remove(baseWrapper.eq(SysUserRole::getUserId, userId));
        return saveBatch(userRoleList);
    }

}
